package cn.ggy.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * 切面类
 */

//将MyLogger配置到IOC容器中
@Component
@Aspect
public class MyLogger {

    //单独配一个类用来当切入点
    @Pointcut("execution(* cn.ggy.service..*.*(..))")
    public void pointcut(){

    }

    //测试前置增强
//    @Before(value = "execution(* cn.ggy.service..*.*(..))")
    @Before("pointcut()")
    public void before(JoinPoint jp){
        //获取当前日期的字符串形式
        String date = dateStr(new Date());
        System.out.println(date+"=======================>>>>>>调用了"+jp.getTarget()+"类的"+jp.getSignature()
        +"方法,参数是:"+ Arrays.toString(jp.getArgs()));
    }

    //测试后置增强
//    @AfterReturning(pointcut = "pointcut()",returning = "result")
    public void after(Object result){
        System.out.println("==========================>>>我是后置增强,返回值是:"+result+"万年薪!");
    }

    //测试异常增强
//    @AfterThrowing(pointcut = "pointcut()",throwing = "e")
    public void exception(Exception e){
        System.err.println("========================>>>>我是异常增强,异常是:"+e.getMessage());
    }

    //测试最终增强
//    @After("pointcut()")
    public void finalAdd(){
        System.out.println("=======================>>>我是最终增强！！");
    }

    //测试环绕增强
    @Around("pointcut()")
    public void around(ProceedingJoinPoint pjp){
        try {
            //前置增强
            System.out.println("===========================>>>前置增强!!!");
            Object result = pjp.proceed();
            //后置增强
            System.out.println("===========================>>>后置增强,返回值是:"+result);
        } catch (Throwable throwable) {
            //异常增强
            System.out.println("===========================>>>异常增强,返回值是:"+throwable.getMessage());
//            throwable.printStackTrace();
        } finally {
            //最终增强
            System.out.println("===========================>>>最终增强!!!");
        }
    }


    //将当前时间以字符串的方式打印出来
    public String dateStr(Date date){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String format = simpleDateFormat.format(date);
        return format;
    }
}
